package com.edu.neusoft.elec_shop.controller;

import com.edu.neusoft.elec_shop.domain.Goods;
import com.edu.neusoft.elec_shop.service.GoodsService;
import com.edu.neusoft.elec_shop.util.AjaxResult;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.List;

@RestController
@RequestMapping("/goods")
@Api(tags = "商品管理接口")
public class GoodsController {

    @Autowired
    private GoodsService goodsService;

    // 添加新的商品
    @PostMapping
    @ApiOperation(value = "添加新商品", notes = "接收商品对象作为请求体并添加到数据库中")
    public AjaxResult addNewGoods(@RequestBody @Valid Goods goods) {
        try {
            goodsService.insert(goods);
            return AjaxResult.success("商品添加成功");
        } catch (Exception e) {
            return AjaxResult.error("商品添加失败：" + e.getMessage());
        }
    }

    // 根据商品ID删除某商品信息
    @DeleteMapping("/{goodsId}")
    @ApiOperation(value = "根据商品ID删除商品", notes = "根据提供的商品ID删除对应的商品信息")
    public AjaxResult deleteGoodsById(@PathVariable("goodsId") @Valid Long goodsId) {
        try {
            goodsService.deleteGoodsById(goodsId);
            return AjaxResult.success("商品信息删除成功");
        } catch (Exception e) {
            return AjaxResult.error("商品信息删除失败：" + e.getMessage());
        }
    }

    // 获取所有商品信息
    @GetMapping
    @ApiOperation(value = "获取所有商品信息", notes = "返回数据库中所有商品的信息列表")
    public AjaxResult getAllGoods() {
        try {
            List<Goods> goodsList = goodsService.getAllGoods();
            return AjaxResult.success("获取所有商品信息成功", goodsList);
        } catch (Exception e) {
            return AjaxResult.error("获取所有商品信息失败：" + e.getMessage());
        }
    }
}